package cn.haohaowo;

import cn.haohaowo.entity.Account;
import cn.haohaowo.service.AccountService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by luwancai on 18/5/19.
 * DESC:
 */
@RestController
public class AccountController {

    @Autowired
    private AccountService accountService;


    @RequestMapping("/queryEmailExist")
    public String queryEmailExist(String accountId, String email) {

        JSONObject jsonObject = new JSONObject();
        try {
            Account account = accountService.queryAccountById(Integer.valueOf(accountId));
            jsonObject.put("isExist", false);
            if (null == account) {
                jsonObject.put("isExist", email.equals(account.getEmail()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonObject.toJSONString();

    }

    @RequestMapping("/queryNameExist")
    public String queryNameExist(String userName) {

        JSONObject jsonObject = new JSONObject();
        try {
            Account account = accountService.queryAccount(userName, null);
            jsonObject.put("isExist", false);
            if (null == account) {
                jsonObject.put("isExist", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonObject.toJSONString();

    }

    @RequestMapping("/saveOrUpdateAccount")
    public String saveOrUpdateAccount(String accountJSON) {

        JSONObject result = new JSONObject();
        try {
            result.put("isSuccess", false);
            if (StringUtils.isEmpty(accountJSON)) {
                return result.toJSONString();
            }

            Account account = JSONObject.parseObject(accountJSON, Account.class);
            Account accountTmp = accountService.queryAccount(account.getUserName(), null);
            if (null == accountTmp) {
                accountService.saveAccount(account);
            } else {
                accountService.modifyAccount(account);
            }
            result.put("isExist", true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result.toJSONString();

    }

    @RequestMapping("/queryAccount")
    public String queryAccount(String userName, String password) {

        try {
            if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
                return null;
            }

            Account accountTmp = accountService.queryAccount(userName, password);
            if (null != accountTmp) {
                return JSONObject.toJSONString(accountTmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }




}
